import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

/**
 * @author Steve Duncan
 * opencsv-2.3.jar found at http://opencsv.sourceforge.net/
 */
public class CSVFile {
	private static ArrayList<Mutant> data = new ArrayList<Mutant>();

	public static ArrayList<Mutant> getData() {
		return data;
	}

	public static void setData(ArrayList<Mutant> data) {
		CSVFile.data.clear();  // clear array list before writing a new one.
		CSVFile.data = data;
	}

	public static void readCSV(String file){
		CSVReader reader;
		String name;
		try {
			reader = new CSVReader(new FileReader(file));
			String [] nextLine;
			while ((nextLine = reader.readNext()) != null) {
				// nextLine[] is an array of values from the line
				double numbers[] = new double[60];
				name = nextLine[0];
				for(int i = 0; i< nextLine.length - 2; i++){
					numbers[i] = Double.parseDouble(nextLine[i+1]);
				}
				data.add(new Mutant(name, numbers));
			}			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}		

	public static void writeCSV(String file){
		CSVWriter writer = null;
		String[] dataArray = new String[61];
		double numbers[] = new double[60];

		try {
			writer = new CSVWriter(new FileWriter(file), ',');
			for(int i = 0; i < data.size(); i++){
				// get data from arraylist				
				dataArray[0] = data.get(i).getName();
				numbers = data.get(i).getData();

				for(int j = 0; j < numbers.length; j++)
					dataArray[j+1] = String.valueOf(numbers[j]);

				if(dataArray != null)
					writer.writeNext(dataArray);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String inputFile = "resources/Melanopsin_Mutants.csv";
		String outputFile = "resources/Melanopsin_Mutants_Output.csv";
		readCSV(inputFile);
		writeCSV(outputFile);

		/*double d[] = {0.0, 1.0};
		Mutant x = new Mutant("391A, A392",d);
		Mutant y = new Mutant();
		Mutant z = new Mutant("391A, A395",d, true);

		ArrayList<Mutant> newdata = new ArrayList<Mutant>();
		newdata.add(x);
		newdata.add(y);
		newdata.add(z);

		CSVFile.setData(newdata); */		

		boolean print = false;
		// print contents of what was read
		if(print){
			for(int j = 0; j < data.size(); j++)
				System.out.println(data.get(j).toString());	
		}	
	}
}

